#include "AuthManager.h"
#include <QCryptographicHash>
#include <QDateTime>
#include <QThread>
#include <QDebug>
#include <QRandomGenerator>


AuthManager::AuthManager(QObject* parent) : QObject(parent), m_tokenExpiry(QDateTime::currentDateTime())
{
}

AuthManager::~AuthManager() = default;

QVariantMap AuthManager::userMap() const
{
    QReadLocker locker( & m_lock);
    return m_currentUser.toVariantMap();
}

void AuthManager::login(const SysUser& userInfo)
{
    QWriteLocker locker( & m_lock);

    m_currentUser = userInfo;
    m_authenticated = true;
    // 生成访问令牌
    QString rawToken = QString("%1:%2:%3")
                       .arg(userInfo.account,
                            QDateTime::currentDateTime().toString(Qt::ISODate),
                            QString::number(QRandomGenerator::global()->generate()));

    m_accessToken = QCryptographicHash::hash(
                        rawToken.toUtf8(), QCryptographicHash::Sha256
                    ).toHex();

    // 设置令牌有效期(1小时)
    m_tokenExpiry = QDateTime::currentDateTime().addSecs(3600);

    // emit userChanged();
    // emit authChanged(true);
}

void AuthManager::logout()
{
    QWriteLocker locker( & m_lock);

    m_currentUser = SysUser();
    m_accessToken.clear();
    m_refreshToken.clear();
    m_authenticated = false;

    emit userChanged();
    emit authChanged(false);
}

bool AuthManager::isAuthenticated() const
{
    QReadLocker locker( & m_lock);
    return m_authenticated;
}

SysUser AuthManager::currentUser() const
{
    QReadLocker locker( & m_lock);
    return m_currentUser;
}

QString AuthManager::accessToken() const
{
    QReadLocker locker( & m_lock);
    return m_accessToken;
}

void AuthManager::refreshToken()
{
    QWriteLocker locker( & m_lock);

    if (!m_authenticated) return;

    // 刷新令牌逻辑
    QString rawToken = QString("%1:%2:%3")
                       .arg(m_currentUser.account,
                            QDateTime::currentDateTime().toString(Qt::ISODate),
                            QString::number(QRandomGenerator::global()->bounded(100)));

    m_accessToken = QCryptographicHash::hash(
                        rawToken.toUtf8(), QCryptographicHash::Sha256
                    ).toHex();

    m_tokenExpiry = QDateTime::currentDateTime().addSecs(3600);
}
